package factotyService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import util.Result;

public abstract class AbstractService implements ServiceProcess {
	protected HttpServletRequest req = null;
	protected HttpServletResponse res = null;
	protected JSONObject data = null;
	protected Result result = null;
	
	public AbstractService() {
		// TODO Auto-generated constructor stub
	}
	
	public AbstractService(HttpServletRequest req, HttpServletResponse res) throws IOException, JSONException {
		// TODO Auto-generated constructor stub
		this.req = req;
		this.res = res;
		//_do();
	}
	
	//流程控制
	public void _do() throws IOException, JSONException{
		this.unpack();
		this.check();
		this.hand();
		this.pack();
	}
	
	@Override
	public void unpack() throws IOException, JSONException {
		// TODO Auto-generated method stub
		this.req.setCharacterEncoding("utf-8");
		BufferedReader br = null;
		br = this.req.getReader();
		StringBuffer sb = new StringBuffer();
		String temp = null;
		while((temp = br.readLine()) != null) {
			sb.append(temp);
		}
		if(br != null){
			br.close();
		}
		temp = null;
		String result = sb.toString();
		//！！！！！！！！！！！！！！！！ajax编码一次，java解码两次，解决ajax post请求中文乱码！！
		result = URLDecoder.decode(URLDecoder.decode(result,"UTF-8"),"UTF-8");
		System.out.println("请求Json为："+result);
		JSONObject json = new JSONObject(result);
		this.data = json;
	}
	
	/*@Override
	public void check(){
		// TODO Auto-generated method stub
		System.out.println("父类方法check");
	}

	@Override
	public void hand() {
		// TODO Auto-generated method stub
		System.out.println("父类方法hand");
	}*/
	
	@Override
	public void pack() throws IOException {
		// TODO Auto-generated method stub
		this.res.setCharacterEncoding("utf-8");
		this.res.setContentType("text/html;charset=UTF-8");
		JSONObject result_json = null;
		result_json = new JSONObject(this.result);
		PrintWriter pw = null;
		pw = this.res.getWriter();
		System.out.println("响应结果为：" + result_json.toString());
		pw.write(result_json.toString());
		if(pw != null){
			pw.close();
		}
		System.out.println("写出json字符串完毕");
	}

}
